package com.cn.tcc;

import com.cn.entity.Storage;
import com.cn.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class StorageTCCActionImpl implements StorageTCCAction {
    @Autowired
    private StorageMapper storageMapper;
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long productID, Integer count) {
        Storage storage=storageMapper.selectById(productID);
        if (storage.getResidue()<count){
            throw new RuntimeException("库存不足");
        }
        storageMapper.decrease(productID, count);
        ResultHolder.setResult(StorageTCCAction.class, ctx.getXid(), "p");

        return true;
    }
    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
//        提交过后删除标记
        if (ResultHolder.getResult(StorageTCCAction.class ,ctx.getXid() )==null) {
            return true;
        }

        Long productId= Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count= Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(productId, count);
        ResultHolder.removeResult(StorageTCCAction.class, ctx.getXid());
        return true;
    }
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        //        会滚过后删除标记
        if (ResultHolder.getResult(StorageTCCAction.class ,ctx.getXid() )==null) {
            return true;
        }
        Long productId= Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count= Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(productId, count);
        ResultHolder.removeResult(StorageTCCAction.class, ctx.getXid());

        return true;
    }
}
